Ext.namespace("Microtraining.Admin.Question");
Mt = Microtraining.Admin;
Mt.Question={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示题目的视图相对题目列表Grid的位置
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示题目信息页(或者打开新窗口)
			 */
			IsFix:0
		},
        /**
         * 在线编辑器类型。
         * 1:CkEditor,2:KindEditor,3:xhEditor
         * 配合Action的变量配置$online_editor
         */
        OnlineEditor:4
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Question.Cookie.get('View.Direction')){
			Mt.Question.Config.View.Direction=Mt.Question.Cookie.get('View.Direction');
		}
		if (Mt.Question.Cookie.get('View.IsFix')!=null){
			Mt.Question.Config.View.IsFix=Mt.Question.Cookie.get('View.IsFix');
		}
        if (Ext.util.Cookies.get('OnlineEditor')!=null){
            Mt.Question.Config.OnlineEditor=parseInt(Ext.util.Cookies.get('OnlineEditor'));
        }

	}
};
/**
 * Model:数据模型
 */
Mt.Question.Store = {

  optionStore:new Ext.data.ArrayStore({
    fields : [
      {name : 'oid',type : 'int'},
      {name : 'title',type : 'string'},
      {name : 'current',type : 'int'},
    ]
  }),
	/**
	 * 题目
	 */
	questionStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
                {name: 'question_id',type: 'int'},
                {name: 'company_id',type: 'int'},
                {name: 'company_name',type: 'string'},
                {name: 'question_title',type: 'string'},
                {name: 'answer',type: 'string'},
                {name: 'point',type: 'float'},
                {name: 'options_json',type: 'string'},
                {name: 'options_jsonShow',type:'string'},
                {name: 'paperStr',type: 'string'},
                {name: 'paper_title',type: 'string'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Question.Config.PageSize;
					Ext.apply(options.params, Mt.Question.View.Running.questionGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),
    /**
     * 企业
     */
    companyStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/company.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'companys',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'company_id'
        }, [
            {name: 'company_id', mapping: 'company_id'},
            {name: 'company_name', mapping: 'company_name'}
        ])
    }),
    /**
     * 试卷
     */
    selectPaperStore:new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalCount',
            successProperty: 'success',
            root: 'data',remoteSort: true,
            fields : [
                {name: 'paper_id',type: 'int'},
                {name: 'company_id',type: 'int'},
                {name: 'company_name',type: 'string'},
                {name: 'paper_title',type: 'string'},
                {name: 'point',type: 'float'},
                {name: 'questionStr',type: 'string'}
            ]}
        ),
        writer: new Ext.data.JsonWriter({
            encode: false
        }),
        listeners : {
            beforeload : function(store, options) {
                if (Ext.isReady) {
                    Ext.apply(options.params, Mt.Question.View.Running.selectPaperWindow.paperGrid.filter);//保证分页也将查询条件带上
                }
            },
            load : function(records,options){
                if (records&&records.data&&records.data.items) {
                    var selData    = Mt.Question.View.Running.selectPaperWindow.selData;//选中的试卷
                    var data       = records.data.items;
                    //把已经推荐的试卷选中
                    var sm=Mt.Question.View.Running.selectPaperWindow.paperGrid.sm;
                    var rows=Mt.Question.View.Running.selectPaperWindow.paperGrid.getView().getRows();
                    for(var i=0;i<rows.length;i++){
                        if(selData[data[i]['data'].paper_id]){
                            sm.selectRow(i, true);
                        }
                    }
                }
            }
        }
    }),
    /**
     * 企业
     */
    companyStoreForCombo:new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'home/admin/src/httpdata/company.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'companys',
            autoLoad: true,
            totalProperty: 'totalCount',
            idProperty: 'company_id'
        }, [
            {name: 'company_id', mapping: 'company_id'},
            {name: 'company_name', mapping: 'company_name'}
        ])
    })
};
/**
 * View:题目显示组件
 */
Mt.Question.View={
  OptionView:{
    /**
     *  当前创建的选项编辑窗口
     */
    edit_window:null,
    /**
     * 编辑窗口：新建或者修改选项
     */
    EditWindow:Ext.extend(Ext.Window,{
      constructor : function(config) {
        config = Ext.apply({
          /**
           * 自定义类型:保存类型
           * 0:保存窗口,1:修改窗口
           */
          savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,modal: true,
          width : 450,height : 200,minWidth : 400,minHeight : 200,
          layout : 'fit',plain : true,buttonAlign : 'center',
          defaults : {autoScroll : true},
          listeners:{
            beforehide:function(){
              this.editForm.form.getEl().dom.reset();
            }
          },
          items : [
            new Ext.form.FormPanel({
              ref:'editForm',layout:'form',
              labelWidth : 100,labelAlign : "center",
              bodyStyle : 'padding:5px 5px 0',align : "center",
              api : {},
              defaults : {
                xtype : 'textfield',anchor:'98%'
              },
              items : [
                {xtype: 'hidden',name : 'oid',ref:'../oid'},
                {fieldLabel : '选项',name : 'title',ref:'../otitle',xtype : 'textarea',allowBlank : false }, 
                // {xtype: 'hidden',name : 'current',ref:'../ocurrent'},
                {fieldLabel : '正确答案',hiddenName : 'current',xtype : 'combo',ref:'../current',mode : 'local',triggerAction : 'all',lazyRender : true,editable: false,allowBlank : false,
                  store : new Ext.data.SimpleStore({
                    fields : ['value', 'text'],
                    data : [['0', '否'], ['1', '是']]
                  }),emptyText: '请选择...',
                  valueField : 'value',// 值
                  displayField : 'text',// 显示文本
                }
              ]
            })
          ],
          buttons : [{
            text: "",ref : "../saveBtn",scope:this,
            handler : function() {

              if (!this.editForm.getForm().isValid()) {
                return;
              }
              editWindow=this;

              var option_store = Mt.Question.Store.optionStore;
              var OptionRecord = Ext.data.Record.create([
                     {name: 'oid', type: 'int'},
                     {name: 'title', type: 'string'},
                     {name: 'current', type: 'int'},
                 ]);

              if (this.savetype==0){//保存

                var id = 1;
                 while(option_store.findExact('oid',id) != -1){
                  id++;
                 }

                 var record = new OptionRecord({
                     oid: id,
                     title: editWindow.otitle.getValue(),
                     current: editWindow.current.getValue()
                 });  
                 option_store.add(record);

              }else{//修改
               var oid = Mt.Question.View.Running.optionGrid.getSelectionModel().getSelected().id; 
               var record = option_store.getById(oid);

               record.set('title',editWindow.otitle.getValue());
               record.set('current',editWindow.current.getValue());
               record.commit();
              }
              editWindow.editForm.getForm().reset()
              editWindow.hide(); 
            }
          }, {
            text : "取 消",scope:this,
            handler : function() {
              this.hide();
            }
          }, {
            text : "重 置",ref:'../resetBtn',scope:this,
            handler : function() {
              this.editForm.form.loadRecord(Mt.Question.View.Running.optionGrid.getSelectionModel().getSelected());

            }
          }]
        }, config);
        Mt.Question.View.OptionView.EditWindow.superclass.constructor.call(this, config);
      }
    }),
    /**
     * 查询条件
     */
    filter:null,
    /**
     * 视图：选项列表
     */
    Grid:Ext.extend(Ext.grid.GridPanel, {
      constructor : function(config) {
        config = Ext.apply({
          store : Mt.Question.Store.optionStore,height:210,
          sm : this.sm,
          frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
          loadMask : true,stripeRows : true,headerAsText : false,
          defaults : {autoScroll : true},
          cm : new Ext.grid.ColumnModel({
            defaults:{
              width:120,sortable : true
            },
            columns : [
              this.sm,
              {header : '标识',dataIndex : 'oid',hidden:true},
              {header : '选项',dataIndex : 'title',width:500},
              {header : '正确答案',dataIndex : 'current',renderer:function(value){
                  return value == 1 ? "是" : "否"
                }
              },
            ]
          }),
          tbar : {
            xtype : 'container',layout : 'anchor',
            height : 27,style:'font-size:14px',
            defaults : {
              height : 27,anchor : '100%'
            },
            items : [
              new Ext.Toolbar({
                defaults:{
                  scope: this
                },
                items : [
                  {
                    text: '反选',iconCls : 'icon-reverse',
                    handler: function(){
                      this.onReverseSelect();
                    }
                  },'-',{
                    text : '添加选项',iconCls : 'icon-add',
                    handler : function() {
                      this.addOption();
                    }
                  },'-',{
                    text : '修改选项',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                      this.updateOption();
                    }
                  },'-',{
                    text : '删除选项', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
                    handler : function() {
                      this.deleteOption();
                    }
                  },'-',
                  {
                    text : '切换正确答案', ref: '../../btnAnswer',iconCls : 'icon-edit',disabled : true,
                    handler : function() {
                       this.changeAnswer();
                    }
                  },'-']}
            )]
          } 
        }, config);
        /**
         * 选项数据模型获取数据Direct调用
         */
        Mt.Question.View.OptionView.Grid.superclass.constructor.call(this, config);
      },
      /**
       * 行选择器
       */
      sm : new Ext.grid.CheckboxSelectionModel({
        listeners : {
          selectionchange:function(sm) {
            // 判断删除和更新按钮是否可以激活
            this.grid.btnRemove.setDisabled(sm.getCount() < 1);
            this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
            this.grid.btnAnswer.setDisabled(sm.getCount() != 1);
          }
        }
      }),
      /**
       * 查询符合条件的选项
       */
      doSelectOption : function() {
        
      },
      /**
       * 反选
       */
      onReverseSelect:function() {
        for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
          if (this.sm.isSelected(i)) {
            this.sm.deselectRow(i);
          }else {
            this.sm.selectRow(i, true);
          }
        }
      },
      /**
       * 新建选项
       */
      addOption : function(){
        if (Mt.Question.View.OptionView.edit_window==null){
          Mt.Question.View.OptionView.edit_window=new Mt.Question.View.OptionView.EditWindow();
        }
        Mt.Question.View.OptionView.edit_window.resetBtn.setVisible(false);
        Mt.Question.View.OptionView.edit_window.saveBtn.setText('保 存');
        Mt.Question.View.OptionView.edit_window.setTitle('添加选项');
        Mt.Question.View.OptionView.edit_window.savetype=0;
        Mt.Question.View.OptionView.edit_window.oid.setValue("");
        Mt.Question.View.OptionView.edit_window.show(); 
      },
      /**
       * 编辑选项时先获得选中的选项信息
       */
      updateOption : function() {
        if (Mt.Question.View.OptionView.edit_window==null){
          Mt.Question.View.OptionView.edit_window=new Mt.Question.View.OptionView.EditWindow();
        }
        Mt.Question.View.OptionView.edit_window.saveBtn.setText('修 改');
        Mt.Question.View.OptionView.edit_window.resetBtn.setVisible(true);
        Mt.Question.View.OptionView.edit_window.setTitle('修改选项');
        Mt.Question.View.OptionView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
        Mt.Question.View.OptionView.edit_window.savetype=1;

        Mt.Question.View.OptionView.edit_window.show(); 
      },
      changeAnswer : function() {
        var option_store = Mt.Question.Store.optionStore;
        var option = this.getSelectionModel().getSelected().data;

        var oid = Mt.Question.View.Running.optionGrid.getSelectionModel().getSelected().id;
        var record = option_store.getById(oid);
        
        if (option.current == 1) {
          record.set('current',0);
        }else{
          record.set('current',1);
        }
        record.commit();
      },
      /**
       * 删除选项
       */
      deleteOption : function() {
        Ext.Msg.confirm('提示', '确实要删除所选的选项吗?', this.confirmDeleteOption,this);
      },
      /**
       * 确认删除选项
       */
      confirmDeleteOption : function(btn) {
        if (btn == 'yes') {

          var oid = Mt.Question.View.Running.optionGrid.getSelectionModel().getSelected().data.oid;
          var option_store = Mt.Question.Store.optionStore;

          var del_oid ="";
          var selectedRows    = this.getSelectionModel().getSelections();
          for ( var flag = 0; flag < selectedRows.length; flag++) {
            del_oid = selectedRows[flag].data.oid;
            option_store.removeAt(option_store.find('oid',del_oid));
          }
          this.doSelectOption();
          Ext.Msg.alert("提示", "删除成功！");
        }
      }
    })
  },
	/**
	 * 编辑窗口：新建或者修改题目
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					}
          ,
          afterrender:function(){
            switch (Mt.Question.Config.OnlineEditor)
            {
                case 1:
                    ckeditor_replace_question_title();
                    // ckeditor_replace_answer();
                    // ckeditor_replace_options_json();
                    break
                case 2:
                    Mt.Question.View.EditWindow.KindEditor_question_title = KindEditor.create('textarea[name="question_title"]',{width:'98%',minHeith:'350px', filterMode:true});
                    // Mt.Question.View.EditWindow.KindEditor_answer = KindEditor.create('textarea[name="answer"]',{width:'98%',minHeith:'350px', filterMode:true});
                    // Mt.Question.View.EditWindow.KindEditor_options_json = KindEditor.create('textarea[name="options_json"]',{width:'98%',minHeith:'350px', filterMode:true});
                    break
                case 3:
                    pageInit_question_title();
                    // pageInit_answer();
                    // pageInit_options_json();
                    break
                default:
                    this.editForm.question_title.setWidth("98%");
                    pageInit_ue_question_title();
                    // this.editForm.answer.setWidth("98%");
                    // pageInit_ue_answer();
                    // this.editForm.options_json.setWidth("98%");
                    // pageInit_ue_options_json();
            }
          }
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
                            {xtype: 'hidden',name : 'question_id',ref:'../question_id'},
                            /*{xtype: 'hidden',name : 'company_id',ref:'../company_id'},
                            {
                                 fieldLabel : '企业',xtype: 'combo',name : 'company_name',ref : '../company_name',
                                 store:Mt.Question.Store.companyStoreForCombo,emptyText: '请选择企业',itemSelector: 'div.search-item',
                                 loadingText: '查询中...',width: 570, pageSize:Mt.Question.Config.PageSize,
                                 displayField:'company_name',grid:this,
                                 mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                                 forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                                 tpl:new Ext.XTemplate(
                                     '<tpl for="."><div class="search-item">',
                                         '<h3>{company_name}</h3>',
                                     '</div></tpl>'
                                 ),
                                 listeners:{
                                     'beforequery': function(event){delete event.combo.lastQuery;}
                                 },
                                 onSelect:function(record,index){
                                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                                        this.grid.company_id.setValue(record.data.company_id);
                                        this.grid.company_name.setValue(record.data.company_name);
                                        this.collapse();
                                     }
                                 }
                            },*/
                            {fieldLabel : '题目',name : 'question_title',xtype : 'textarea',id:'question_title',ref:'question_title'},
                            // {fieldLabel : '答案',name : 'answer'},
                            {fieldLabel : '分值',name : 'point',xtype : 'numberfield'},
                            {fieldLabel : '试卷',name : 'paper_title',xtype : 'textarea'},
                            {xtype: 'hidden',name : 'options_json',ref:'../options_json'},
                            Mt.Question.View.Running.optionGrid
                            // {fieldLabel : '选项',name : 'options_json',xtype : 'textarea',id:'options_json',ref:'options_json'}
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {
            switch (Mt.Question.Config.OnlineEditor)
            {
                case 1:
                    if (CKEDITOR.instances.question_title) this.editForm.question_title.setValue(CKEDITOR.instances.question_title.getData());
                    // if (CKEDITOR.instances.answer) this.editForm.answer.setValue(CKEDITOR.instances.answer.getData());
                    // if (CKEDITOR.instances.options_json) this.editForm.options_json.setValue(CKEDITOR.instances.options_json.getData());
                    break
                case 2:
                    if (Mt.Question.View.EditWindow.KindEditor_question_title)this.editForm.question_title.setValue(Mt.Question.View.EditWindow.KindEditor_question_title.html());
                    // if (Mt.Question.View.EditWindow.KindEditor_answer)this.editForm.answer.setValue(Mt.Question.View.EditWindow.KindEditor_answer.html());
                    // if (Mt.Question.View.EditWindow.KindEditor_options_json)this.editForm.options_json.setValue(Mt.Question.View.EditWindow.KindEditor_options_json.html());
                    break
                case 3:
                    if (xhEditor_question_title)this.editForm.question_title.setValue(xhEditor_question_title.getSource());
                    // if (xhEditor_answer)this.editForm.answer.setValue(xhEditor_answer.getSource());
                    // if (xhEditor_options_json)this.editForm.options_json.setValue(xhEditor_options_json.getSource());
                    break
                default:
                    if (ue_question_title)this.editForm.question_title.setValue(ue_question_title.getContent());
                    // if (ue_answer)this.editForm.answer.setValue(ue_answer.getContent());
                    // if (ue_options_json)this.editForm.options_json.setValue(ue_options_json.getContent());
            }
						if (!this.editForm.getForm().isValid()) {
							return;
						}

            var option_store = Mt.Question.View.Running.optionGrid.store;
            if (option_store.getCount() < 2) {
              Ext.Msg.alert("提示", "请添加至少2个选项");
              return;
            };

            var optsions_json=new Array();
            var has_current_option=false;

            option_store.each(function(record) {
                optsions_json.push(record.data);
                if (!has_current_option) {
                  has_current_option = record.data.current;
                };
            });

            if (!has_current_option) {
              Ext.Msg.alert("提示", "请添加至少1个正确选项");
              return;
            };
            this.editForm.getForm().findField('options_json').setValue(Ext.encode(optsions_json));

						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServiceQuestion.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Question.View.Running.questionGrid.doSelectQuestion();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServiceQuestion.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Question.View.Running.questionGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Question.View.Running.questionGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected());
                        // switch (Mt.Question.Config.OnlineEditor)
                        // {
                        //     case 2:
                        //         if (Mt.Question.View.EditWindow.KindEditor_options_json) Mt.Question.View.EditWindow.KindEditor_options_json.html(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
                        //         break
                        //     case 3:
                        //         break
                        //     default:
                        //         if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
                        // }
            switch (Mt.Question.Config.OnlineEditor)
            {
                case 1:
                    if (CKEDITOR.instances.question_title) CKEDITOR.instances.question_title.setData(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_title);
                    // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.answer);
                    // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
                    break
                case 2:
                    if (Mt.Question.View.EditWindow.KindEditor_question_title) Mt.Question.View.EditWindow.KindEditor_question_title.html(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_title);
                    // if (Mt.Question.View.EditWindow.KindEditor_answer) Mt.Question.View.EditWindow.KindEditor_answer.html(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.answer);
                    // if (Mt.Question.View.EditWindow.KindEditor_options_json) Mt.Question.View.EditWindow.KindEditor_options_json.html(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
                    break
                case 3:
                    if (xhEditor_question_title) xhEditor_question_title.setSource(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_title);
                    // if (xhEditor_answer) xhEditor_answer.setSource(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.answer);
                    // if (xhEditor_options_json) xhEditor_options_json.setSource(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
                    break
                default:
                    if (ue_question_title) ue_question_title.setContent(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_title);
                    // if (ue_answer) ue_answer.setContent(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.answer);
                    // if (ue_options_json) ue_options_json.setContent(Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.options_json);
            }

					}
				}]
			}, config);
			Mt.Question.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示题目详情
	 */
	QuestionView:{
		/**
		 * Tab页：容器包含显示与题目所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择题目！');
									return false;
								}
								Mt.Question.Config.View.IsShow=1;
								Mt.Question.View.Running.questionGrid.showQuestion();
								Mt.Question.View.Running.questionGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Question.View.QuestionView.Tabs.superclass.constructor.call(this, config);

				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Question.Config.View.Direction==1)||(Mt.Question.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabQuestionDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
                         '    <tr class="entry"><td class="head">企业</td><td class="content">{company_name}</td></tr>',
                         '    <tr class="entry"><td class="head">题目</td><td class="content">{question_title}</td></tr>',
                         // '    <tr class="entry"><td class="head">答案</td><td class="content">{answer}</td></tr>',
                         '    <tr class="entry"><td class="head">分值</td><td class="content">{point}</td></tr>', 
                         '    <tr class="entry"><td class="head">试卷</td><td class="content">{paper_title}</td></tr>', 
						 '</table>'
					 ]}
				);
                this.add(
                    {title: '其他',iconCls:'tabs'}
                );
			}
		}),
		/**
		 * 窗口:显示题目信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看题目",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Question.View.QuestionView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Question.Config.View.IsShow=0;
							Mt.Question.View.Running.questionGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Question.View.Running.questionGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增题目',scope:this,
						handler : function() {this.hide();Mt.Question.View.Running.questionGrid.addQuestion();}
					},{
						text: '修改题目',scope:this,
						handler : function() {this.hide();Mt.Question.View.Running.questionGrid.updateQuestion();}
					}]
				}, config);
				Mt.Question.View.QuestionView.Window.superclass.constructor.call(this, config);
			}
		})
	},
    /**
     * 视图：试卷
     */
    PaperView:{
        SelectPaperWindow:Ext.extend(Ext.Window,{
            constructor : function(config) {
                config = Ext.apply({
                    selData:null,//选中的试卷
                    oldData:null,//已关联的试卷
                    title:"选择试卷",updateData:null,closeAction:"hide",constrainHeader:true,maximizable:true,collapsible:true,
                    width:720,minWidth:720,height:560,minHeight:450,layout:'fit',plain : true,buttonAlign : 'center',
                    defaults : {autoScroll : true,},
                    listeners:{
                        beforehide:this.doHide
                    },
                    items : [new Mt.Question.View.PaperView.PaperGrid({ref:"paperGrid"})],
                    buttons : [ {
                        text: "确定",ref : "../saveBtn",scope:this,
                        handler : function() {
                            var selData = this.selData;
                            var oldData = this.oldData;
                            //题目标识
                            var question_id=Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_id;
                            var condition={'selData':selData,"oldData":oldData,"question_id":question_id};
                            Ext.Msg.show({
                                title: '请等待', msg: '操作进行中，请稍后...',
                                animEl: 'loading', icon: Ext.Msg.WARNING,
                                closable: true, progress: true, progressText: '', width: 300
                            });
                            ExtServiceQuestion.updateQuestionPaper(condition,function(provider, response) {
                                if (response.result.success==true) {
                                    var msg = "操作成功！";
                                    if(response.result.del){
                                        msg += "<font color=red>取消</font>了<font color=red>"+response.result.del+"</font>件关联货品,";
                                    }
                                    if(response.result.add){
                                        msg += "<font color=green>添加</font>了<font color=green>"+response.result.add+"</font>件关联货品";
                                    }
                                    Ext.Msg.alert('提示', msg);
                                } else {
                                    Mt.Question.Store.selectPaperStore.removeAll();
                                    Ext.Msg.alert('提示', '操作失败！');
                                }
                                Mt.Question.View.Running.selectPaperWindow.hideWindow();
                                Mt.Question.View.Running.questionGrid.doSelectQuestion();
                            });
                        }
                    }, {
                        text : "取 消",scope:this,
                        handler : function() {
                            this.hide();
                        }
                    }]
                }, config);
                Mt.Question.View.PaperView.SelectPaperWindow.superclass.constructor.call(this, config);
            },
            /**
            * 根据选择的试卷,改变标题
            */
            changeTitle: function(){
                var title   = "选择 试卷";
                var selData = this.selData;
                var count   = this.objElCount(selData);
                if(count){
                    title += "（已经选择了<font color=green>"+count+"</font>件试卷）";
                }else{
                    title += "（尚未选择任何试卷）";
                }
                this.setTitle(title);
            },
            /**
            * 判断自定义对象元素个数
            */
            objElCount: function(obj){
                var count = 0;
                for(var n in obj){count++}
                return count;
            },
            /**
             * 确认取消图片处理
             * con:选择窗口
             */
            doHide: function (con) {
                //window初始化时会调用,此时con为null
                if(con){
                    Ext.MessageBox.show({
                        title:'提示',msg:'确定要取消么?<br /><font color=red>(所做操作将不会保存!)</font>',buttons:Ext.MessageBox.YESNO,icon:Ext.MessageBox.QUESTION,
                        params:{con:con},
                        fn:function(btn,text,opt) {
                            if(btn=='yes') {
                                con.hideWindow();
                            }
                        }
                    });
                    return false;
                }
            },
            /**
             * 隐藏窗口
             */
            hideWindow: function () {
                //移除beforehide事件，为了防止hide时进入死循环
                this.un('beforehide',this.doHide);
                this.hide();
                this.addListener('beforehide',this.doHide);
            }
        }),
        PaperGrid:Ext.extend(Ext.grid.GridPanel,{
            constructor : function(config) {
                config = Ext.apply({
                    /**
                     * 查询条件
                     */
                    filter:null,question_id:null,region : 'center',store : Mt.Question.Store.selectPaperStore,sm : this.sm,
                    trackMouseOver : true,enableColumnMove : true,columnLines : true,loadMask : true,stripeRows : true,headerAsText : false,
                    loadMask : {msg : '加载数据中，请稍候...'},
                    defaults : {autoScroll : true},
                    cm : new Ext.grid.ColumnModel({
                        defaults:{width:120,sortable : true},
                        columns : [
                            this.sm,
                            {header : '标识',dataIndex : 'paper_id',hidden:true},
                            // {header : '企业',dataIndex : 'company_name',hidden:true},
                            {header : '分值',dataIndex : 'point'},
                            {header : '试卷名',dataIndex : 'paper_title'}
                        ]
                    }),
                    tbar : {
                        xtype : 'container',layout : 'anchor',
                        height : 27,style:'font-size:14px',
                        defaults : {
                            height : 27,anchor : '100%'
                        },
                        items : [
                            new Ext.Toolbar({
                                enableOverflow: true,width : 80,ref:'menus',
                                defaults : {
                                    xtype : 'textfield',
                                    listeners : {
                                       specialkey : function(field, e) {
                                            if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectPaper();
                                        }
                                    }
                                },
                                items : [
                                    {text: '全部',ref:'../../isSelect',xtype:'tbsplit',iconCls : 'icon-view',enableToggle: true,
                                         toggleHandler:function(item, checked){
                                            if (checked==true){
                                                Mt.Question.View.Running.selectPaperWindow.paperGrid.topToolbar.menus.select.setChecked(true);
                                            }else{
                                                Mt.Question.View.Running.selectPaperWindow.paperGrid.topToolbar.menus.all.setChecked(true);
                                            }
                                        },
                                        menu: {
                                            items: [
                                                {text: '全部',checked: true,group: 'isSelect',ref:'../../all',
                                                    checkHandler: function(item, checked){
                                                        if (checked){
                                                            Mt.Question.View.Running.selectPaperWindow.paperGrid.isSelect.setText(item.text);
                                                            Mt.Question.View.Running.selectPaperWindow.paperGrid.filter.selectType=0;
                                                        }
                                                        Mt.Question.View.Running.selectPaperWindow.paperGrid.doSelectPaper();
                                                    }
                                                },
                                                {text: '未选择',checked: false,group: 'isSelect',ref:'../../unselect',
                                                      checkHandler: function(item, checked){
                                                          if (checked){
                                                              Mt.Question.View.Running.selectPaperWindow.paperGrid.isSelect.setText(item.text);
                                                              Mt.Question.View.Running.selectPaperWindow.paperGrid.filter.selectType=2;
                                                          }
                                                          Mt.Question.View.Running.selectPaperWindow.paperGrid.doSelectPaper();
                                                      }
                                                },
                                                {text: '已选择',checked: false,group: 'isSelect',ref:'../../select',
                                                      checkHandler: function(item, checked){
                                                          if (checked){
                                                              Mt.Question.View.Running.selectPaperWindow.paperGrid.isSelect.setText(item.text);
                                                              Mt.Question.View.Running.selectPaperWindow.paperGrid.filter.selectType=1;
                                                          }
                                                          Mt.Question.View.Running.selectPaperWindow.paperGrid.doSelectPaper();
                                                    }
                                                }
                                             ]
                                        }
                                    },
                                    // '企业','&nbsp;&nbsp;',{ref: '../pcompany_id',xtype: 'combo',
                                    //      store:Mt.Question.Store.companyStoreForCombo,hiddenName : 'company_id',
                                    //      emptyText: '请选择企业',itemSelector: 'div.search-item',
                                    //      loadingText: '查询中...',width:280,pageSize:Mt.Question.Config.PageSize,
                                    //      displayField:'company_name',valueField:'company_id',
                                    //      mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                                    //      forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                                    //      tpl:new Ext.XTemplate(
                                    //          '<tpl for="."><div class="search-item">',
                                    //          '<h3>{company_name}</h3>',
                                    //          '</div></tpl>'
                                    //      )
                                    // },'&nbsp;&nbsp;',
                                    '试卷名','&nbsp;&nbsp;',{ref: '../ppaper_title'},'&nbsp;&nbsp;',
                                    {
                                        xtype : 'button',text : '查询',scope: this,
                                        handler : function() {
                                            this.doSelectPaper();
                                        }
                                    },
                                    {
                                        xtype : 'button',text : '重置',scope: this,
                                        handler : function() {
                                            // this.topToolbar.pcompany_id.setValue("");
                                            this.topToolbar.ppaper_title.setValue("");
                                            this.filter={};
                                            this.doSelectPaper();
                                        }
                                    }
                                ]
                            })
                        ]
                    },
                    bbar: new Ext.PagingToolbar({
                        pageSize: Mt.Question.Config.PageSize,
                        store: Mt.Question.Store.selectPaperStore,
                        scope:this,autoShow:true,displayInfo: true,
                        displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
                        emptyMsg: "无显示数据",
                        items: [
                            {xtype:'label', text: '每页显示'},
                            {xtype:'numberfield', value:Mt.Question.Config.PageSize,minValue:1,width:35,
                                style:'text-align:center',allowBlank:false,
                                listeners:
                                {
                                    change:function(Field, newValue, oldValue){
                                        var num = parseInt(newValue);
                                        if (isNaN(num) || !num || num<1)
                                        {
                                            num = Mt.Question.Config.PageSize;
                                            Field.setValue(num);
                                        }
                                        Mt.Question.Config.PageSize = num;
                                        this.ownerCt.ownerCt.doSelectPaper();
                                    },
                                    specialKey :function(field,e){
                                        if (e.getKey() == Ext.EventObject.ENTER){
                                            var num = parseInt(field.getValue());
                                            if (isNaN(num) || !num || num<1)
                                            {
                                                num = Mt.Question.Config.PageSize;
                                            }
                                            Mt.Question.Config.PageSize = num;
                                            this.ownerCt.ownerCt.doSelectPaper();
                                        }
                                    }
                                }
                            },
                            {xtype:'label', text: '个'}
                        ]
                    })
                }, config);
                //初始化显示试卷列表
                //this.doSelectPaper();
                Mt.Question.Store.selectPaperStore.proxy=new Ext.data.DirectProxy({
                    api: {read:ExtServiceQuestion.queryPageQuestionPaper}
                });
                Mt.Question.View.PaperView.PaperGrid.superclass.constructor.call(this, config);
            },
            /**
            * SelectionModel
            */
            sm : new Ext.grid.CheckboxSelectionModel({
                listeners : {
                    selectionchange:function(sm) {
                        Mt.Question.View.Running.selectPaperWindow.changeTitle();
                        Mt.Question.View.Running.selectPaperWindow.paperGrid.changeFilter();
                    },
                    rowselect: function(sm, rowIndex, record) {
                        var selPaperWin  = Mt.Question.View.Running.selectPaperWindow;
                        var selData      = selPaperWin.selData;
                        var oldData      = selPaperWin.oldData;
                        var paper_id     = record.data.paper_id;
                        //添加该货品ID
                        selData[paper_id] = true;
                        //判断是否是已关联的货品
                        if(oldData[paper_id]){
                            oldData[paper_id].active = true;
                        }
                    },
                    rowdeselect: function(sm, rowIndex, record) {
                        var selPaperWin  = Mt.Question.View.Running.selectPaperWindow;
                        var selData      = selPaperWin.selData;
                        var oldData      = selPaperWin.oldData;
                        var paper_id     = record.data.paper_id;
                        //删除该货品ID
                        delete selData[paper_id];
                        //判断是否是已关联的货品
                        if(oldData[paper_id]){
                            oldData[paper_id].active = false;
                        }
                    }
                }
            }),
            doSelectPaper : function() {
                var tmp_selPaper=this.filter.selPaper;
                if (this.topToolbar){
                    var question_id=this.question_id;
                    if (!this.filter.selectType)this.filter.selectType=0;
                    // var pcompany_id = this.topToolbar.pcompany_id.getValue();
                    var ppaper_title = this.topToolbar.ppaper_title.getValue();
                    this.filter       ={ 'paper_title':ppaper_title,'question_id':question_id,'selectType':this.filter.selectType};
                }
                this.filter.selPaper=tmp_selPaper;
                var condition = {'start':0,'limit':Mt.Question.Config.PageSize};
                Ext.apply(condition,this.filter);
                ExtServiceQuestion.queryPageQuestionPaper(condition,function(provider, response) {
                    if (response.result&&response.result.data) {
                        var result           = new Array();
                        result['data']       =response.result.data;
                        result['totalCount'] =response.result.totalCount;
                        Mt.Question.Store.selectPaperStore.loadData(result);
                    } else {
                        Mt.Question.Store.selectPaperStore.removeAll();
                        Ext.Msg.alert('提示', '无符合条件的试卷！');
                    }
                });
            },
            /**
            * 修改查询条件
            */
            changeFilter: function(){
                var selData =Mt.Question.View.Running.selectPaperWindow.selData;
                var selArr  = new Array();
                for(var x in selData){
                    selArr.push(x);
                }
                this.filter.selPaper = selArr.join(",");
            }
        }),
    },
	/**
	 * 窗口：批量上传题目
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传题目数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传题目Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow           =this;
							validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result             = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadQuestion',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Question.View.Running.questionGrid.doSelectQuestion();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					}]
				}, config);
			Mt.Question.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 视图：题目列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Question.Store.questionStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:120,sortable : true
					},
					columns : [
						this.sm,
                        {header : '标识',dataIndex : 'question_id',hidden:true},
                        {header : '企业',dataIndex : 'company_name',hidden:true},
                        {header : '题目',dataIndex : 'question_title',width:500},
                        // {header : '答案',dataIndex : 'answer'},
                        {header : '分值',dataIndex : 'point'},
                        {header : '试卷名',dataIndex : 'paper_title'}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 100,
							defaults : {
								xtype : 'textfield',
								listeners : {
								   specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectQuestion();
									}
								}
							},
							items : [
                               /* '企业','&nbsp;&nbsp;',{ref: '../qcompany_id',xtype: 'combo',
                                     store:Mt.Question.Store.companyStoreForCombo,hiddenName : 'company_id',
                                     emptyText: '请选择企业',itemSelector: 'div.search-item',
                                     loadingText: '查询中...',width:280,pageSize:Mt.Question.Config.PageSize,
                                     displayField:'company_name',valueField:'company_id',
                                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                                     tpl:new Ext.XTemplate(
                                         '<tpl for="."><div class="search-item">',
                                         '<h3>{company_name}</h3>',
                                         '</div></tpl>'
                                     )
                                },'&nbsp;&nbsp;',*/
                                '题目','&nbsp;&nbsp;',{ref: '../qquestion_title'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectQuestion();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                                        // this.topToolbar.qcompany_id.setValue("");
                                        this.topToolbar.qquestion_title.setValue("");
										this.filter={};
										this.doSelectQuestion();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加题目',iconCls : 'icon-add',
									handler : function() {
										this.addQuestion();
									}
								},'-',{
									text : '修改题目',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updateQuestion();
									}
								},'-',{
									text : '删除题目', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deleteQuestion();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importQuestion();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入题目',iconCls : 'icon-import',scope:this,handler:function(){this.importQuestion()}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportQuestion();
									}
								},'-',{
                  text : '下载导入模版',iconCls : 'icon-export',
                  handler : function() {
                    this.exportQuestionMode();
                  }
                },'-',{
									xtype:'tbsplit',text: '查看题目', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showQuestion()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hideQuestion();Mt.Question.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Question.Cookie.set('View.IsFix',Mt.Question.Config.View.IsFix);}}
										]}
								}/*,'-',{
                                    text : '选择试卷',ref:'../../tpaper',iconCls : 'icon-edit',disabled : true,
                                    handler : function() {
                                        if(Mt.Question.View.Running.selectPaperWindow==null || Mt.Question.View.Running.selectPaperWindow.hidden){
                                            this.showPaper();
                                        }else{
                                            this.hidePaper();
                                        }
                                    }
                                }*/,'-']}
					)]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Question.Config.PageSize,
					store: Mt.Question.Store.questionStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Question.Viewport){
								if (Mt.Question.Config.View.IsShow==1){
									Mt.Question.View.IsSelectView=1;
								}
								this.ownerCt.hideQuestion();
								Mt.Question.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Question.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Question.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Question.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectQuestion();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Question.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Question.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectQuestion();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示题目列表
			this.doSelectQuestion();
			Mt.Question.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的题目信息Tab页
			Mt.Question.View.Running.viewTabs=new Mt.Question.View.QuestionView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					this.grid.btnRemove.setDisabled(sm.getCount() < 1);
					this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
          // this.grid.tpaper.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hideQuestion();
						Mt.Question.Config.View.IsShow=0;
                        this.grid.hidePaper();
					}else{
						if (Mt.Question.View.IsSelectView==1){
							Mt.Question.View.IsSelectView=0;
							this.grid.showQuestion();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Question.Config.View.IsShow==1){
							Mt.Question.View.IsSelectView=1;
						}
						this.grid.hideQuestion();
						Mt.Question.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Question.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showQuestion();
				this.tvpView.toggle(true);
			}else{
				this.hideQuestion();
				Mt.Question.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			   Mt.Question.Config.View.IsFix=1;
			}else{
			   Mt.Question.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Question.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Question.Config.View.IsShow==1){
			   this.hideQuestion();
			   Mt.Question.Config.View.IsShow=0;
			}
			this.showQuestion();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的题目
		 */
		doSelectQuestion : function() {
			if (this.topToolbar){
                // var qcompany_id = this.topToolbar.qcompany_id.getValue();
                var qquestion_title = this.topToolbar.qquestion_title.getValue();
                this.filter       ={'question_title':qquestion_title};
			}
			var condition = {'start':0,'limit':Mt.Question.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServiceQuestion.queryPageQuestion(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result           = new Array();
					result['data']       =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Question.Store.questionStore.loadData(result);
				} else {
					Mt.Question.Store.questionStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的题目！');
				}
			});
		},
		/**
		 * 显示题目视图
		 * 显示题目的视图相对题目列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Question.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Question.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Question.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Question.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Question.View.Running.viewTabs);
					break;
			}
			Mt.Question.Cookie.set('View.Direction',Mt.Question.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Question.Config.View.IsFix==0)&&(Mt.Question.Config.View.IsShow==1)){
					this.showQuestion();
				}
				Mt.Question.Config.View.IsFix=1;
				Mt.Question.View.Running.questionGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Question.Config.View.IsShow=0;
				this.showQuestion();
			}
		},
		/**
		 * 显示题目
		 */
		showQuestion : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择题目！');
				Mt.Question.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Question.Config.View.IsFix==0){
				if (Mt.Question.View.Running.view_window==null){
					Mt.Question.View.Running.view_window=new Mt.Question.View.QuestionView.Window();
				}
				if (Mt.Question.View.Running.view_window.hidden){
					Mt.Question.View.Running.view_window.show();
					Mt.Question.View.Running.view_window.winTabs.hideTabStripItem(Mt.Question.View.Running.view_window.winTabs.tabFix);
					this.updateViewQuestion();
					this.tvpView.toggle(true);
					Mt.Question.Config.View.IsShow=1;
				}else{
					this.hideQuestion();
					Mt.Question.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Question.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Question.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Question.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Question.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Question.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Question.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Question.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Question.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Question.View.Running.viewTabs);
					}
					break;
			}
			this.hideQuestion();
			if (Mt.Question.Config.View.IsShow==0){
				Mt.Question.View.Running.viewTabs.enableCollapse();
				switch(Mt.Question.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewQuestion();
				this.tvpView.toggle(true);
				Mt.Question.Config.View.IsShow=1;
			}else{
				Mt.Question.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏题目
		 */
		hideQuestion : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Question.View.Running.view_window!=null){
				Mt.Question.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前题目显示信息
		 */
		updateViewQuestion : function() {

			if (Mt.Question.View.Running.view_window!=null){
				Mt.Question.View.Running.view_window.winTabs.tabQuestionDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Question.View.Running.viewTabs.tabQuestionDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建题目
		 */
		addQuestion : function() {
      if (Mt.Question.View.Running.optionGrid==null){
        Mt.Question.View.Running.optionGrid = new Mt.Question.View.OptionView.Grid();
      }
      Mt.Question.View.Running.optionGrid.store.loadData([]);

			if (Mt.Question.View.Running.edit_window==null){
				Mt.Question.View.Running.edit_window=new Mt.Question.View.EditWindow();
			}
			Mt.Question.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Question.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Question.View.Running.edit_window.setTitle('添加题目');
			Mt.Question.View.Running.edit_window.savetype=0;
			Mt.Question.View.Running.edit_window.question_id.setValue("");
      switch (Mt.Question.Config.OnlineEditor)
      {
          case 1:
              if (CKEDITOR.instances.question_title) CKEDITOR.instances.question_title.setData("");
              // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData("");
              // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData("");
              break
          case 2:
              if (Mt.Question.View.EditWindow.KindEditor_question_title) Mt.Question.View.EditWindow.KindEditor_question_title.html("");
              // if (Mt.Question.View.EditWindow.KindEditor_answer) Mt.Question.View.EditWindow.KindEditor_answer.html("");
              // if (Mt.Question.View.EditWindow.KindEditor_options_json) Mt.Question.View.EditWindow.KindEditor_options_json.html("");
              break
          case 3:
              break
          default:
              if (ue_question_title)ue_question_title.setContent("");
              // if (ue_answer)ue_answer.setContent("");
              // if (ue_options_json)ue_options_json.setContent("");
      }
			Mt.Question.View.Running.edit_window.show();
			Mt.Question.View.Running.edit_window.maximize();
		},
		/**
		 * 编辑题目时先获得选中的题目信息
		 */
		updateQuestion : function() {
      if (Mt.Question.View.Running.optionGrid==null){
        Mt.Question.View.Running.optionGrid = new Mt.Question.View.OptionView.Grid();
      }
			if (Mt.Question.View.Running.edit_window==null){
				Mt.Question.View.Running.edit_window=new Mt.Question.View.EditWindow();
			}
			Mt.Question.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Question.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Question.View.Running.edit_window.setTitle('修改题目');
			Mt.Question.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Question.View.Running.edit_window.savetype=1;
      
      var data = Ext.decode(this.getSelectionModel().getSelected().data.options_json);
      Mt.Question.Store.optionStore.loadData(data);
      switch (Mt.Question.Config.OnlineEditor)
      {
          case 1:
              if (CKEDITOR.instances.question_title) CKEDITOR.instances.question_title.setData(this.getSelectionModel().getSelected().data.question_title);
              // if (CKEDITOR.instances.answer) CKEDITOR.instances.answer.setData(this.getSelectionModel().getSelected().data.answer);
              // if (CKEDITOR.instances.options_json) CKEDITOR.instances.options_json.setData(this.getSelectionModel().getSelected().data.options_json);
              break
          case 2:
              if (Mt.Question.View.EditWindow.KindEditor_question_title) Mt.Question.View.EditWindow.KindEditor_question_title.html(this.getSelectionModel().getSelected().data.question_title);
              // if (Mt.Question.View.EditWindow.KindEditor_answer) Mt.Question.View.EditWindow.KindEditor_answer.html(this.getSelectionModel().getSelected().data.answer);
              // if (Mt.Question.View.EditWindow.KindEditor_options_json) Mt.Question.View.EditWindow.KindEditor_options_json.html(this.getSelectionModel().getSelected().data.options_json);
              break
          case 3:
              if (xhEditor_question_title)xhEditor_question_title.setSource(this.getSelectionModel().getSelected().data.question_title);
              // if (xhEditor_answer)xhEditor_answer.setSource(this.getSelectionModel().getSelected().data.answer);
              // if (xhEditor_options_json)xhEditor_options_json.setSource(this.getSelectionModel().getSelected().data.options_json);
              break
          default:
              if (ue_question_title)ue_question_title.setContent(this.getSelectionModel().getSelected().data.question_title);
              // if (ue_answer)ue_answer.setContent(this.getSelectionModel().getSelected().data.answer);
              // if (ue_options_json)ue_options_json.setContent(this.getSelectionModel().getSelected().data.options_json);
      }
			Mt.Question.View.Running.edit_window.show();
			Mt.Question.View.Running.edit_window.maximize();
		},
		/**
		 * 删除题目
		 */
		deleteQuestion : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的题目吗?', this.confirmDeleteQuestion,this);
		},
		/**
		 * 确认删除题目
		 */
		confirmDeleteQuestion : function(btn) {
			if (btn == 'yes') {
				var del_question_ids ="";
				var selectedRows    = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_question_ids=del_question_ids+selectedRows[flag].data.question_id+",";
				}
				ExtServiceQuestion.deleteByIds(del_question_ids);
				this.doSelectQuestion();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
        /**
         * 显示试卷
         */
        showPaper:function(){
            if (Mt.Question.View.Running.selectPaperWindow==null){
                Mt.Question.View.Running.selectPaperWindow=new Mt.Question.View.PaperView.SelectPaperWindow();
            }
            var question_id=Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.question_id;

            //关联试卷ID组成的字符串
            var paperStr    = Mt.Question.View.Running.questionGrid.getSelectionModel().getSelected().data.paperStr;
            var selData    = {};
            var oldData    = {};
            if(paperStr){
                var paperArr = paperStr.split(",");
                for(var i=0;i<paperArr.length;i++){
                    selData[paperArr[i]] = true;//ture为已存在的关联货品
                    oldData[paperArr[i]] = {};
                    oldData[paperArr[i]].active = true;
                }
            }
            var selPaperWin     = Mt.Question.View.Running.selectPaperWindow;
            var selPaperGrid    = selPaperWin.paperGrid;
            selPaperWin.selData = selData;
            selPaperWin.oldData = oldData;
            selPaperWin.changeTitle();//根据选择的货品,修改标题

            selPaperGrid.question_id = question_id;
            if (selPaperWin.hidden){
                // Mt.Question.View.Running.selectPaperWindow.paperGrid.topToolbar.pcompany_id.setValue("");
                Mt.Question.View.Running.selectPaperWindow.paperGrid.topToolbar.ppaper_title.setValue("");
                selPaperGrid.filter = {selPaper:paperStr};
                selPaperGrid.topToolbar.menus.all.setChecked(true);
                selPaperGrid.isSelect.toggle(false);
                Mt.Question.Store.selectPaperStore.removeAll();
            }
            selPaperGrid.doSelectPaper();
            selPaperWin.show();
        },
        /**
         * 隐藏试卷
         */
        hidePaper:function(){
            if (Mt.Question.View.Running.selectPaperWindow!=null){
                Mt.Question.View.Running.selectPaperWindow.hide();
            }
        },
		/**
		 * 导出题目
		 */
		exportQuestion : function() {
      var question_ids ="";
      var selectedRows  = this.getSelectionModel().getSelections();
      for ( var flag = 0; flag < selectedRows.length; flag++) {
        question_ids=question_ids+selectedRows[flag].data.question_id+",";
      }
      var condition = {'question_ids':question_ids};
      Ext.apply(condition,this.filter);
			ExtServiceQuestion.exportQuestion(condition,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
    /**
     * 下载导入模版
     */
    exportQuestionMode : function() {
      window.open("attachment/question/question.xls");
    },
		/**
		 * 导入题目
		 */
		importQuestion : function() {
			if (Mt.Question.View.current_uploadWindow==null){
				Mt.Question.View.current_uploadWindow=new Mt.Question.View.UploadWindow();
			}
			Mt.Question.View.current_uploadWindow.show();
		}
	}),
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Question.View.Running.questionGrid=new Mt.Question.View.Grid();
			if (Mt.Question.Config.View.IsFix==0){
				Mt.Question.View.Running.questionGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Question.View.Running.questionGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Question.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Question.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前题目Grid对象
		 */
		questionGrid:null,
    optionGrid:null,

        /**
         * 推荐试卷
         */
        selectPaperWindow:null,
		/**
		 * 显示题目信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
    option_edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Question.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Question.Init();
	/**
	 * 题目数据模型获取数据Direct调用
	 */
	Mt.Question.Store.questionStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServiceQuestion.queryPageQuestion}
	});
	/**
	 * 题目页面布局
	 */
	Mt.Question.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Question.View.Panel()]
	});
	Mt.Question.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});